package org.qqcui.designpattern.patterns.interpreter;

import java.sql.Statement;
import java.util.Map;
import java.util.Stack;

/**
 * 计算器业务类
 *
 * @author cuiqingqiang
 * @version 1.0
 * @date 2022/5/7 11:07
 **/
public class Calculator {

    private Expression expression;

    public Calculator(String expr) {
        // 记录运算先后顺序
        Stack<Expression> stack = new Stack<>();
        // 将表达式拆分成字符数组
        char[] chars = expr.toCharArray();

        Expression left;
        Expression right;
        for (int i = 0; i < chars.length; i++) {
            switch (chars[i]) {
                case '+':
                    // 加号左边
                    left = stack.pop();
                    // 加号右边
                    right = new VarExpression(String.valueOf(chars[++i]));
                    // 构造加法表达式
                    stack.push(new AddExpression(left, right));
                    break;
                case '-':
                    // 加号左边
                    left = stack.pop();
                    // 加号右边
                    right = new VarExpression(String.valueOf(chars[++i]));
                    // 构造减法表达式
                    stack.push(new SubExpression(left, right));
                    break;
                default:
                    stack.push(new VarExpression(String.valueOf(chars[i])));
                    break;
            }
        }
        this.expression = stack.pop();
    }

    /**
     * 计算表达式结果
     * @param var
     * @return
     */
    public int run(Map<String, Integer> var) {
        return this.expression.interpreter(var);
    }
}
